package com.gxa.saas.core.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

public class RestUtils {

    private static RestTemplate restTemplate;
    static {
        //OkHttp3ClientHttpRequestFactory性能比较好，需要引入jar
//        restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        restTemplate = new RestTemplate();
    }

    /**
     *
     * @param url
     * @param headers 自定义请求头
     * @return
     */
    public static Map postWithParams(String url,Map<String,String> headers,MultiValueMap params){
        //请求头（包括请求类型）
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        if(headers!=null) {
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                httpHeaders.set(entry.getKey(),entry.getValue());
            }
        }

        //请求类型
//        HttpEntity:spring提供的一个传递Http请求的实体类型
        HttpEntity httpEntity = new HttpEntity(params,httpHeaders);
        //通过post方式发送请求的方法
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);
        return map;
    }

    /*
    * 通过参数发起远程请求的重载方法
    * */
    public static Map postWithParams(String url,MultiValueMap params){
        Map map = postWithParams(url,null,params);
        return map;
    }
}
